package com.iqilu.ksd.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.AddPaikeActivity;
import com.iqilu.ksd.activity.LoginActivity;
import com.iqilu.ksd.activity.PaikeActivity;
import com.iqilu.ksd.adapter.PaikeAdapter;
import com.iqilu.ksd.bean.PaikeBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.utils.JSONUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;

import okhttp3.Call;

/**
 * Created by Coofee on 2016/10/11.
 */

public class PaikeFragment extends BaseFragment {

    private static final String TAG = "PaikeFragment";

    private ArrayList<PaikeBean> list;

    private int page;
    private PaikeAdapter adapter;

    private RelativeLayout layMain;
    private RelativeLayout layHead;
    private ImageView btLeft;
    private ImageView btRight;
    private TextView tvTitle;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private ImageView imgEmpty;
    private RelativeLayout layEmpty;
    private ImageView btReload;
    private RelativeLayout layLoading;

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_common, null);
        layMain = getView(view, R.id.lay_main);
        layHead = getView(view, R.id.lay_head);
        btLeft = getView(view, R.id.bt_left);
        btRight = getView(view, R.id.bt_right);
        tvTitle = getView(view, R.id.tv_title);
        setZHTypeface(tvTitle);
        xRefreshView = getView(view, R.id.xRefreshView);
        rvList = getView(view, R.id.rv_list);
        imgEmpty = getView(view, R.id.img_empty);
        layEmpty = getView(view,R.id.lay_empty);
        btReload = getView(view,R.id.bt_reload);
        layLoading = getView(view, R.id.lay_loading);
//        layMain.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_orange));
        initHead();

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        layLoading = getView(view, R.id.lay_loading);
        layLoading.setVisibility(View.VISIBLE);

        btReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                layLoading.setVisibility(View.VISIBLE);
                xRefreshView.setVisibility(View.VISIBLE);
                getList();
            }
        });

        adapter = new PaikeAdapter(context);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(context));
        adapter.setOnItemClickListener(new PaikeAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(View view, int position) {
                Intent intent = new Intent(context, PaikeActivity.class);
                intent.putExtra("id", list.get(position).getId());
                startActivity(intent);
            }
        });

        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        rvList.setAdapter(adapter);
        initHead();
        page = 1;
        getList();
        return view;
    }

    private void initHead() {
        btLeft.setVisibility(View.GONE);
        tvTitle.setText(getString(R.string.pk_title));
        btRight.setImageResource(R.drawable.bt_add_paike);
        btRight.setVisibility(View.VISIBLE);
        layHead.setVisibility(View.VISIBLE);
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserBean user = ((MyApplication) getActivity().getApplication()).getUser();
                if (user == null || user.getId() < 1) {
                    startActivity(new Intent(context, LoginActivity.class));
                } else {
                    startActivity(new Intent(context, AddPaikeActivity.class));
                }
            }
        });
    }

    private void getList() {
        String url = Api.URL_CLUE_LIST + "?page=" + page;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
                if (page == 1) {
                    setEmpty();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                afterRequest();
                ArrayList<PaikeBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<PaikeBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        setEmpty();
                        Toast.makeText(context, R.string.list_empty, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list = result;
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    if (result == null || result.size() == 0) {
                        Toast.makeText(context, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list.addAll(result);
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        layEmpty.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private void setEmpty() {
        adapter.setData(null);
        adapter.notifyDataSetChanged();
        layEmpty.setVisibility(View.VISIBLE);
        xRefreshView.setVisibility(View.GONE);
    }

}
